package Solution.problem059;

/**
 * @program Leetcode
 * @description:
 * @author: lishangsheng
 * @create: 2019/05/31 09:44
 */
public class Solution {
    public static int[][] generateMatrix(int n){
        int i=1;
        int[][] matrix=new int[n][n];

        int rowStart = 0;
        int rowEnd = n - 1;
        int colStart = 0;
        int colEnd = n - 1;

        boolean isCols = true;
        boolean isAdd = true;
        int count = 1;
        for (int c = 0; c < n; ) {
            for (int r = 0; r < n; ) {
                matrix[r][c]=i;
                i++;

                //右上角
                if (count % 4 == 1 && isCols && r == rowStart && c == colEnd) {
                    isCols = false;
                    isAdd = true;
                    rowStart++;
                    /*记录转向数量*/
                    count++;
                }

                //最后一行最后一列,右下角
                if (count % 4 == 2 && !isCols && r == rowEnd && c == colEnd) {
                    isCols = true;
                    isAdd = false;
                    colEnd--;
                    count++;
                }

                //最后一行第一列,左下角
                if (count % 4 == 3 && isCols && r == rowEnd && c == colStart) {
                    isCols = false;
                    isAdd = false;
                    rowEnd--;
                    count++;
                }

                //左上角
                if (count % 4 == 0 && !isCols && r == rowStart && c == colStart) {
                    isCols = true;
                    isAdd = true;
                    colStart++;
                    count++;
                }


                if (rowStart > rowEnd || colStart > colEnd) {
                    return matrix;
                }

                if (isCols) {
                    if (isAdd) {
                        c++;
                    } else {
                        c--;
                    }
                } else {
                    if (isAdd) {
                        r++;
                    } else {
                        r--;
                    }
                }
            }
        }

        return matrix;

    }

    public  static void main(String[] args) {
        int[][] result = generateMatrix(1);
        System.out.println(result);
    }
}
